// SlagCar/OrderDetail/OrderDetail.js
let orderBehavior = require('../OrderAdd/orderBehavior')
Page({
  behaviors: [ orderBehavior, ],

  /**
   * 页面的初始数据
   */
  data: {
    /*mainField:[
      {field_id: 'xiangmu;value',type: 'select',label: '项目',selectType: 'project',required: true},
      {field_id: 'reference1_all_delivery;value',type: 'select',label: '工地',selectType: 'delivery',required: true,disabled:false },
      {field_id: 'Order_client_ID;value',type: 'select',label: '所属单位',selectType: 'client',disabled: false},
      {label: '联系方式',children: [
          {field_id: 'gongdilianxiren',type: 'text',placeholder: '联系人'},
          {field_id: 'gongdilianxidianhua',type: 'text',placeholder: '联系电话'},
        ]},
      {label: '订单名称',field_id: 'order_name',type: 'text',placeholder: '订单名称',required: true},
    /!*  {label: '工地价格',required: true,children: [
          {field_id: 'construction_payment',type: 'picker',placeholder: '请选择'},
          {field_id: 'construction_price',type: 'digit',placeholder: '工地价格'},
        ]},*!/
      {label: '开始时间',field_id: 'start_time',type: 'calendar',placeholder: '请选择',required: true,disabled: false},
      {label: '结束时间',field_id: 'end_time',type: 'calendar',placeholder: '请选择',required: true,disabled: false},
      {label: '需要运单号/挖机号',field_id: 'need_fill_order_no',type: 'radio',placeholder: '请选择',radioType: 'order'},
      {label: '需要运单/挖机图片',field_id: 'need_fill_order_img',type: 'radio',placeholder: '请选择',radioType: 'img'},
      // {label: '泥尾需要挖机号',field_id: 'need_fill_excavator_no_end',type: 'radio',placeholder: '请选择',radioType: 'need_fill_excavator_no_end'},
      // {label: '泥尾需要挖机图片',field_id: 'need_fill_excavator_img_end',type: 'radio',placeholder: '请选择',radioType: 'need_fill_excavator_img_end'},
      {label: '需要填写趟次',field_id: 'need_fill_transport_times',type: 'radio',placeholder: '请选择',radioType: 'need_fill_transport_times'},
      {label: '需要填写方数',field_id: 'need_fill_square_number',type: 'radio',placeholder: '请选择',radioType: 'need_fill_square_number'},
      {label: '需要车数控制',field_id: 'need_car_no_control',type: 'radio',placeholder: '请选择',radioType: 'need_car_no_control'},
      {label: '填写车数',field_id: 'fill_car_no',type: 'number',placeholder: '请选择',radioType: 'need_car_no_control'},
    ], //订单主表字段
    destField:[
      {field_id: 'destination_name',type: 'select',label: '消纳场',selectType: 'destination',required: true},
      {field_id: 'Order_client_Name',type: 'select',label: '所属单位',selectType: 'destClient'},
      {label: '联系方式',children: [
          {field_id: 'xiaonachanglianxiren',type: 'text',placeholder: '联系人'},
          {field_id: 'xiaonachanglianxidianhua',type: 'text',placeholder: '联系电话'},
        ]},
      {field_id: 'goods_name',type: 'select',label: '泥种',selectType: 'goods',required: true},
      {label: '工地价格',required: true,children: [
          {field_id: 'construction_payment',type: 'picker',placeholder: '请选择'},
          {field_id: 'construction_price',type: 'digit',placeholder: '工地价格'},
        ]},
      {label: '消纳场价格',required: true,children: [
          {field_id: 'destination_payment',type: 'picker',placeholder: '请选择'},
          {field_id: 'Order_amount',type: 'digit',placeholder: '消纳场价格'},
        ]},
      {label: '司机价格',required: true,children: [
          {field_id: 'driver_payment',type: 'picker',placeholder: '请选择'},
          {field_id: 'driver_price',type: 'digit',placeholder: '司机价格'},
        ]},
      {label: '额外金额',required: false,children: [
          {field_id: 'extra_payment',type: 'picker',placeholder: '请选择'},
          {field_id: 'extra_price',type: 'digit',placeholder: '额外金额'},
        ]},
      {label: '泥尾需要挖机号',field_id: 'need_fill_excavator_no_end',type: 'radio',placeholder: '请选择',radioType: 'need_fill_excavator_no_end'},
      {label: '泥尾需要挖机图片',field_id: 'need_fill_excavator_img_end',type: 'radio',placeholder: '请选择',radioType: 'need_fill_excavator_img_end'},

    ], //消纳场明细表字段
*/
 /*   formData: {

    }, // 工地信息（主表）

    driverAssign: [], //指派人员列表（子表）
    destinationAssign: [
      {
        row_id: 0,
        destination_payment: '应收',
        driver_payment: '应付',
        extra_payment: '应付',
      }
    ],    //泥尾（子表）

    rowData: {},
    driverDetail: [],
    destinationDetail: [],
    addDestination: {}, //新增泥尾数据*/
/*
    /!*弹出层显示标识*!/
    showAddDest: false,   //新增泥尾
    showDelivery: false,  //显示工地选择列表
    showDestination: false, //显示消纳场选择列表
    showGoods: false, //显示泥种选择列表
    showDriver: false,  //显示司机选择列表
    showClient: false,  //显示所属单位列表
    showDestClient: false,  //显示泥尾所属单位列表
    showProject: false,   //显示项目列表

    /!*弹出层显示内容*!/
    deliveryList: [], //工地列表
    destinationList: [], //消纳场列表
    goodsList: [],  //泥种列表
    driverList: [],   //司机列表
    clientList: [],  //所属单位列表
    destClientList: [], //泥尾所属单位列表
    projectList: [],  //项目列表

    /!*搜索数据*!/
    searchValue: {},

    /!*应收应付选择器*!/
    showPicker: false,  //显示应收应付选择器
    columns: ['应收','应付'],
    curtPickerField: '',
    curtPickerIndex: 0,
    defaultPickerValue: '',

    /!*日历*!/
    showCalendar: false,  //显示日历
    defaultDatetimeValue: '',
    resetFlag: false,

    //司机分类选择
    firstActiveIndex: 0,
    secondActiveIndex: 0,
    activeId: [],
    items: [],
    checkAll: false,

    // 231219 yan 车队选择修改为弹出选择器选择
    showDriverPicker: false, //司机车队选择器显示
    carTeamColumns: [
      {values:[],defColumns: 0,}, //一级车队
      {values: [],defColumns: 0,} //二级车队
    ],  //车队选择器选项
    crtDriver: [],  //过滤车队显示的司机
    driverPickerValue: [],  //选择器选择的值
    // 231219 end
    addDestDriver: []*/
  },

/*  //列表弹出
  bindShow(e){
    let {type,index} = e.currentTarget.dataset,
      obj = {};
    if (type === 'delivery') obj.showDelivery = true;
    if (type === 'destination') obj.showDestination = true;
    if (type === 'goods') obj.showGoods = true;
    if (type === 'client') obj.showClient = true;
    if (type === 'destClient') obj.showDestClient = true;
    if (type === 'carTeam') obj.showDriverPicker = true;
    if (type === 'project') obj.showProject = true;

    obj.curtPickerIndex = index;
    this.setData(obj)
  },
  // 列表弹窗关闭
  bindClose(){
    this.setData({showDelivery: false,showDestination: false,showDriver: false,showGoods: false,showPicker: false,showClient: false,showDestClient: false,showProject: false})
  },
  //泥尾弹窗关闭
  bindCloseDest(){
    this.setData({showAddDest: false})
  },


  //搜索输入框变化
  searchChange(e){
    let {type} = e.currentTarget.dataset,
      {searchValue} = this.data;
    searchValue[type] = e.detail;
    this.setData({searchValue});
  },
  // 搜索
  bindSearch(e){
    let {type} = e.currentTarget.dataset,
      {searchValue} = this.data,
      val = searchValue[type] || '',
      obj = {
        delivery: {listName: 'deliveryList',fieldName: ['delivery_name','Order_client_ID;value']},
        destination: {listName: 'destinationList',fieldName: ['destination_name','Order_client_ID;value']},
        driver: {listName: 'crtDriver',fieldName: 'text'},
        goods: {listName: 'goodsList',fieldName: 'goods_name'},
        client: {listName: 'clientList',fieldName: 'customer_name'},
        destClient: {listName: 'destClientList',fieldName: 'customer_name'},
        project: {listName: 'projectList',fieldName: 'xiangmumingchen'},
      },
      {listName,fieldName} = obj[type],
      list = this.data[listName];
    list.forEach(item => {
      let text = item[fieldName];
      if (typeof fieldName === 'object'){
        text = [];
        fieldName.forEach(ite => {item[ite] && text.push(item[ite])});
        text = text.join('');
      }
      item.isHide = text && text.indexOf(val) < 0
    })
    this.setData({[listName]: list});
    if (type === 'driver') this.isCheckedAll(); //司机搜索，检查是否全选，勾起
  },
  //获取项目
  getProject(){
    wx.showLoading({mask: true});
    let where = [{CompareValue: true, CompareWith: "e_xiangmulixiang.is_used", Operator: "=", or: 0}]
    this.getCustomData('e_xiangmulixiang',where).then(res => {
      wx.hideLoading();
      let projectList = res || [];
      this.setData({projectList})
    })

  },
  //获取工地
  getDelivery(){
    return new Promise(resolve => {
      let where = [{CompareValue: true, CompareWith: "all_delivery.is_used", Operator: "=", or: 0}]
      this.getCustomData('all_delivery',where).then(res => {
        let deliveryList = res || [];
        this.setData({deliveryList});
        resolve();
      })
    })
  },
  //获取消纳场
  getDestination(){
    return new Promise(resolve => {
      let where = [{CompareValue: true, CompareWith: "all_destination.is_used", Operator: "=", or: 0}]
      this.getCustomData('all_destination',where).then(res => {
        let destinationList = res || [];
        this.setData({destinationList})
        resolve();
      })
    })
  },
  //获取泥种
  getGoods(){
    return new Promise(resolve => {
      this.getCustomData('goods').then(res => {
        let goodsList = res || [];
        this.setData({goodsList});
        resolve();
      })
    })
  },
  //获取所属单位
  getClient(){
    wx.showLoading({mask: true});
    let where = [{CompareValue: true, CompareWith: "customer.shiweixiuchang", Operator: "=", or: 0}]
    this.getCustomData('customer',where).then(res => {
      wx.hideLoading();
      let clientList = res || [];
      this.setData({clientList})
    })
  },
  //获取泥尾所属单位
  getDestClient(){
    wx.showLoading({mask: true});
    let where = [{CompareValue: true, CompareWith: "customer.gongyingshangdanwei", Operator: "=", or: 0}]
    this.getCustomData('customer',where).then(res => {
      wx.hideLoading();
      let destClientList = res || [];
      this.setData({destClientList})
    })
  },
  //获取司机
  getDriver(){
    return new Promise(resolve => {
      this.getCustomData('e_sijiziliaobiao').then(res => {
        let driverList = res || [],
          {driverDetail} = this.data;
        driverList.forEach(item => {
           let {row_id} = item;
           if (driverDetail.some(item => item.reference1_driver == row_id)) {
             item.checked = true;
           }
        })
        this.setData({driverList});
        resolve();
      })
    })
  },*/
 /* bindSelectProject(e){
    let {item} = e.currentTarget.dataset;
    //231220 yan 增加选择项目映射带出工地、所属单位
    this.setData({
      ['formData.xiangmu']: item.row_id,
      ['formData.reference1_all_delivery']: item.gongdi,
      ['formData.order_name']: item['gongdi;value'],
      ['formData.Order_client_ID']: item.wanglaidanwei,
      ['rowData.xiangmu;value']: item.xiangmumingchen,
      ['rowData.reference1_all_delivery;value']: item['gongdi;value'],
      ['rowData.Order_client_ID;value']: item['wanglaidanwei;value'],
      // ['formData.gongdilianxiren']: item.lianxiren,
      // ['formData.gongdilianxidianhua']: item.lianxidianhua,
      showProject: false
    })
    // 231220 end

  },
  //选择工地
  bindSelectDelivery(e){
    let {item} = e.currentTarget.dataset;
    this.setData({
      ['formData.reference1_all_delivery']: item.row_id,
      // ['formData.Order_client_ID']: item.Order_client_ID,
      ['formData.order_name']: item.delivery_name,
      ['formData.gongdilianxiren']: item.lianxiren,
      ['formData.gongdilianxidianhua']: item.lianxidianhua,
      ['rowData.reference1_all_delivery;value']: item.delivery_name,
      // ['rowData.Order_client_ID;value']: item['Order_client_ID;value'],
      ['rowData.order_name']: item.delivery_name,
      ['rowData.gongdilianxiren']: item.lianxiren,
      ['rowData.gongdilianxidianhua']: item.lianxidianhua,

      showDelivery: false
    })
  },
  //选择消纳场
  bindSelectDestination(e){
    let {item} = e.currentTarget.dataset,
      {curtPickerIndex} = this.data;
    this.setData({
      [`addDestination.reference1_all_destination`]: item.row_id,
      [`addDestination.destination_name`]: item.destination_name,
      [`addDestination.Order_client_ID`]: item.Order_client_ID,
      [`addDestination.Order_client_Name`]: item['Order_client_ID;value'],
      [`addDestination.xiaonachanglianxiren`]: item.lianxiren,
      [`addDestination.xiaonachanglianxidianhua`]: item.lianxidianhua,
      showDestination: false
    })

  },
  bindSelectGoods(e){
    let {item} = e.currentTarget.dataset,
      {curtPickerIndex} = this.data;
    this.setData({
      [`addDestination.reference1_goods`]: item.row_id,
      [`addDestination.goods_name`]: item.goods_name,
      showGoods: false
    })
  },
  bindSelectClient(e){
    let {item,index} = e.currentTarget.dataset,
      {curtPickerIndex} = this.data,
      obj = {showClient: false,showDestClient: false};
    if (curtPickerIndex){
      obj[`addDestination.Order_client_ID`] = item.row_id
      obj['addDestination.Order_client_Name'] = item.customer_name
    }else {
      obj[`formData.Order_client_ID`]=item.row_id
      obj[`rowData.Order_client_ID;value`]=item.customer_name
    }
    this.setData(obj)
  },
  bindSelectDriver(e){
    let {index} = e.currentTarget.dataset,
      {driverList } = this.data;
    this.setData({
      [`driverList[${index}].checked`]: !driverList[index].checked
    })
  },*/
  /*231219 yan 注释 修改为泥尾指派司机
  confirmDriver(){
    let {driverList,driverDetail,activeId } = this.data,
      add = [],del = [];
    activeId.forEach(item => {
      let exit = driverDetail.find(ite => ite.reference1_driver == item);
      if (!exit)add.push({
        details: [],
        entity: {row_id: 0,reference1_driver: item}
      })
    });
    driverDetail.forEach(item => {
      let exit = activeId.find(ite => ite == item.reference1_driver);
      if (!exit) del.push(item.row_id);
    })
    /!*driverList.forEach(item => {
      let {row_id} = item,
        exit = driverDetail.find(item => item.reference1_driver == row_id);
      if (exit && !item.checked) {
         del.push(exit.row_id)
      }
      if (item.checked && !exit){
        add.push({
          details: [],
          entity: {row_id: 0,reference1_driver: row_id}
        })
      }
    });*!/

    wx.showLoading({mask: true});
    let pms = [];
    if (del.length){
      pms.push(this.delData('muck_order_assign_personnel',del.join(',')))
    }
    if (add.length){
      let details = [{
        table_id: 'muck_order_assign_personnel',
        entitys: add
      }];
      let post = {
        table: {
          table_id: 'muck_order_main',
          entitys: [
            {
              details,
              entity: {row_id: this.data.rowData.row_id}
            }
          ]
        }
      }
      // console.log(post);
      pms.push(this.updateCustomData(post))
    }
    if (pms.length){
      Promise.all(pms).then(() => {
        wx.$toast('修改成功');
        this.setData({showDriver: false});
        wx.showLoading({mask: true})
        this.getDetailData().then(() => {
          wx.hideLoading();
        });
      })
    } else {
      wx.hideLoading();
      this.setData({showDriver: false})
    }
  },*/
 /* confirmDriver(){
    let {destinationDetail,curtPickerIndex,activeId } = this.data;
    if (curtPickerIndex === 'addDest'){
      this.setData({addDestDriver: activeId,showDriver: false})
      return
    }
    let add = [],del = [],
      destData = destinationDetail[curtPickerIndex],
      driverDetail = destData.details;  //司机明细表
    activeId.forEach(item => {
      let exit = driverDetail.find(ite => ite.reference1_driver == item);
      if (!exit)add.push({
        details: [],
        entity: {row_id: 0,reference1_driver: item}
      })
    });
    driverDetail.forEach(item => {
      let exit = activeId.find(ite => ite == item.reference1_driver);
      if (!exit) del.push(item.row_id);
    });

    wx.showLoading({mask: true});
    let pms = [];
    if (del.length){
      pms.push(this.delData('muck_order_assign_destination_personnel',del.join(',')))
    }
    if (add.length){
      let details = [{
        table_id: 'muck_order_assign_destination_personnel',
        entitys: add
      }];
      let post = {
        table: {
          table_id: 'muck_order_assign_destination',
          entitys: [
            {
              details,
              entity: {row_id: destData.row_id}
            }
          ]
        }
      }
      // console.log(post);
      pms.push(this.updateCustomData(post))
    }
    if (pms.length){
      Promise.all(pms).then(() => {
        wx.$toast('修改成功');
        this.setData({showDriver: false});
        wx.showLoading({mask: true})
        this.getDestDriverDetl(destData.row_id).then((res) => {
          this.setData({
            [`destinationDetail[${index}].details`]: res
          })
          wx.hideLoading();
        });
      })
    } else {
      wx.hideLoading();
      this.setData({showDriver: false})
    }
  },*/
  //231219 end


/*  //单选项变化
  bindRadioChange(e){
    let {type} = e.currentTarget.dataset,
      value = e.detail;
    if (type === 'order'){
      this.data.formData.need_fill_order_no = value;
      this.data.formData.need_fill_excavator_no = value;
    }else if (type === 'img'){
      this.data.formData.need_fill_order_img = value;
      this.data.formData.need_fill_excavator_img = value;
    }else {
      this.data.formData[type] = value;
    }
  },*/

/*  //显示应收应付弹窗
  bindShowPicker(e){
    let {field,index} = e.currentTarget.dataset;
    this.data.curtPickerField = field;
    this.data.curtPickerIndex = index;
    // let def = field === 'construction_payment' ?  this.data.formData[field] : this.data.addDestination[field],
    let def = this.data.addDestination[field],
      defIndex = this.data.columns.indexOf(def);
    console.log(defIndex);
    this.setData({defaultPickerValue: defIndex,showPicker: true});

  },*/
 /* //确认选择选择器
  bindConfirmPicker(e){
    let {value} = e.detail,
      {curtPickerField,curtPickerIndex} = this.data,
      obj = {showPicker: false};
    if (curtPickerField === 'construction_payment') {
      obj[`formData.${curtPickerField}`] = value;
      obj[`rowData.${curtPickerField}`] = value;
    }else {
      obj[`addDestination.${curtPickerField}`] = value;
    }
    this.setData(obj)

  },*/

 /* bindShowCalendar(e){
    let {field} = e.currentTarget.dataset;
    this.data.curtPickerField = field;
    let def = this.data.rowData[field];
    this.setData({
      showCalendar: !this.data.showCalendar,
      defaultDatetimeValue: def
    })
  },*/
 /* //日期时间选择
  bindSelectDatetime(e){
    let value = e.detail,
      {curtPickerField} = this.data;
    this.setData({
      [`formData.${curtPickerField}`]: value,
      [`rowData.${curtPickerField}`]: value
    });
  },

  //输入框修改
  bindChangeInput(e){
    console.log(e);
    let {value} = e.detail,
      {field,index,type} = e.currentTarget.dataset,
      obj = {};
    console.log(index);
    if (type === 'num')value = value || 0;
    if (index){
      obj[`addDestination.${field}`] = value;
    } else {
      obj[`formData.${field}`] = value;
      obj[`rowData.${field}`] = value;
    }

    this.setData(obj);
  },

  //修改
  bindModify(){
    let {formData,rowData} = this.data;
    if (!Object.keys(formData).length) return;
    let obj = {
      xiangmu: '请选择项目',
      order_name: '请输入订单名称',
      // construction_price: '请输入工地价格',
      // gongdilianxiren: '请输入联系人',
      // gongdilianxidianhua: '请输入联系电话',
    };
    let checkData = {...rowData,...formData}
    let mainFlag = this.checkRequired(checkData,obj);
    if (!mainFlag) return;
    if (formData.need_car_no_control && !Number(formData.fill_car_no)) {
      wx.$toast('请输入车数');
      return
    }
    wx.showLoading({mask: true});
    let post = {
      table: {table_id:'muck_order_main',entitys: [
          {
            details: [],
            entity: {...formData,row_id: this.data.rowData.row_id}
          }
        ]}}
    this.submitData('muck_order_main',post).then(() => {
      wx.$toast('修改成功');
      this.data.formData = {};
    });
  },
*/
  //消纳场使用标识修改
  bindSwitchChange(e){
    let is_used = e.detail,
      {index} = e.currentTarget.dataset;
    let data = {
      row_id: this.data.destinationAssign[index].row_id,
      is_used
    };
    wx.showLoading({mask: true});
    let post = {table:{table_id: 'muck_order_assign_destination',entitys: [
          {
            details: [],
            entity: data
          }
        ]}}
    this.updateCustomData(post).then(() => {
      wx.$toast('修改成功');
      this.setData({
        [`destinationAssign[${index}].is_used`]: is_used
      })
    });
  },

  //修改工地表
  bindModify(){
    let {formData,} = this.data,
      obj = {
        xiangmu: '请选择项目',
        reference1_all_delivery: '请选择工地',
        Order_client_ID: '',  //工地所属单位
        gongdilianxiren: '',
        gongdilianxidianhua: '',
        order_name: '请输入订单名称',
        start_time: '请选择开始时间',
        end_time: '请选择结束时间',
        need_fill_order_no: '',
        need_fill_order_img: '',
        need_fill_excavator_no: '',
        need_fill_excavator_img: '',
        need_fill_transport_times: '',
        need_fill_square_number: '',
        need_car_no_control: '',
        fill_car_no: '',
        is_used: '',
        ZhiDingXieHuoDiZhi: '',
        ZhiDingXieHuoJingDu: '',
        ZhiDingXieHuoWeiDu: '',
        ZhiDingXieHuoDiZhiXiaoNaChang: '',
        YanShiXieHuoFenZhongShu: '',
        TuZhiWeiZhiLieBiao: '',
        XuYaoTianTuZhiWeiZhi: ''
      };
    let mainData = this.getSubmitData(formData,obj);
    if (!mainData) return;
    if (mainData.need_car_no_control && !Number(mainData.fill_car_no)) {
      wx.$toast('请输入车数');
      return
    }
    wx.showLoading({mask: true});
    let post = {
      table: {table_id:'muck_order_main',entitys: [
          {
            details: [],
            entity: {...mainData,row_id: formData.row_id}
          }
        ]}}
    this.updateCustomData(post).then(() => {
      wx.$toast('修改成功');
    });
  },
  //修改消纳场
  bindModifyDestination(e){
    let {destinationAssign,formData} = this.data,
      {index} = e.currentTarget.dataset,
      data = destinationAssign[index],
      obj2 = {
        reference1_all_destination: '请选择消纳场',
        Order_client_ID: '',  //消纳场所属单位
        xiaonachanglianxiren: '',
        xiaonachanglianxidianhua: '',
        reference1_goods: '请选择泥种',
        construction_payment: '',
        construction_price: '请输入工地价格',
        destination_payment: '',
        Order_amount: '请输入消纳场价格',
        driver_payment: '',
        driver_price: '请输入司机价格',
        extra_payment: '',
        extra_price: '',    //额外价格
        need_fill_excavator_no_end: '',
        need_fill_excavator_img_end: '',
        need_fill_order_no_end: '',
        need_fill_order_img_end: '',
        is_used: ''
      };
    console.log(formData);
    let destData = this.getSubmitData(data,obj2);
    if (!destData) return;
    let details = !data.row_id && this.fmtDestDriverDetl(data.details) || [],
      post = {
        table: {
          table_id:'muck_order_assign_destination',
          entitys: [
            {
              details: [{
                table_id: 'muck_order_assign_destination_personnel',
                entitys: details
              }],
              entity: {...destData,row_id: data.row_id || 0,parent_row_id: formData.row_id}
            }
          ]
        }
      }
      wx.showLoading({mask: true});
      this.updateCustomData(post).then(() => {
        wx.$toast('修改成功')
        this.getDetailData();
      })
  },

  bindShowAddDest(){
    this.setData({showAddDest: true})
  },
  //提交新增泥尾
  bindAddDestination(e){
    let {addDestination,row_id,addDestDriver} = this.data;
    addDestination.parent_row_id = row_id;
    let obj2 = {
      reference1_all_destination: '请选择消纳场',
      // xiaonachanglianxiren: '请输入消纳场联系人',
      // xiaonachanglianxidianhua: '请输入消纳场联系电话',
      reference1_goods: '请选择泥种',
      construction_price: '请输入工地价格',
      Order_amount: '请输入消纳场价格',
      driver_price: '请输入司机价格',
      // extra_price: '请输入额外价格',
    }

    let flag = this.checkRequired(addDestination,obj2);
    if (!flag) {
      return
    }
    delete addDestination.destination_name;
    delete addDestination.goods_name;
    delete addDestination.Order_client_Name;

    let entitys = [{
      details: [],
      entity: addDestination
    }]
    if (addDestDriver.length){
      let arr = [];
      addDestDriver.forEach(item =>{
        arr.push({
          details: [],
          entity: {
            row_id: 0,
            reference1_driver: item
          }
        })
      });
      entitys[0].details = [
        {
          table_id: 'muck_order_assign_destination_personnel',
          entitys: arr
        }
      ]
    }
    wx.showLoading({mask: true});
    let post = {table:{table_id: 'muck_order_assign_destination',entitys}}
    this.submitData('muck_order_assign_destination',post).then(() => {
      wx.$toast('新增成功');
      this.setData({
        showAddDest: false,
        addDestination: {...this.data.destinationDefData},
        addDestDriver: []
      });
      this.getDetailData();
    });
  },

  //提交
  bindSubmit(){
    let {formData,destinationAssign,driverAssign} = this.data;
    let obj = {
        reference1_all_delivery: '请选择工地',
        order_name: '请输入订单名称',
        construction_price: '请输入工地价格',
        start_time: '请选择开始时间',
        end_time: '请选择结束时间',
      },
      obj2 = {
        reference1_all_destination: '请选择消纳场',
        reference1_goods: '请选择泥种',
        Order_amount: '请输入消纳场价格',
        driver_price: '请输入司机价格',
        // extra_price: '请输入额外价格',
      },
      destDetail = [],driverDetail = [];
    let mainFlag = this.checkRequired(formData,obj);
    if (!mainFlag) return;
    console.log(formData.fill_car_no);
    if (formData.need_car_no_control && !formData.fill_car_no) {
      wx.$toast('请输入车数');
      return
    }
    if (!driverAssign.length) {
      wx.$toast('请添加指派人员');
      return
    }
    if (!destinationAssign.length) {
      wx.$toast('请添加泥尾');
      return
    }
    let destFlag = true;
    destinationAssign.forEach(item => {
      let flag = destFlag && this.checkRequired(item,obj2);
      if (!flag) {
        destFlag = false;
        return
      }
      delete item.destination_name;
      delete item.goods_name;
      destDetail.push({
        details: [],
        entity: item
      })
    });
    driverAssign.forEach(item =>{
      driverDetail.push({
        details: [],
        entity: item
      })
    })
    if (!destFlag) return;

    let details = [
      {
        table_id: 'muck_order_assign_destination',
        entitys: destDetail
      },
      {
        table_id: 'muck_order_assign_personnel',
        entitys: driverDetail
      },
    ];

    delete formData.delivery_name;
    let post = {
      table: {
        table_id: 'muck_order_main',
        entitys: [
          {
            details,
            entity: formData
          }
        ]
      }
    }
    console.log('提交传入参数',post);
    wx.showLoading({mask: true});
    this.updateCustomData(post).then(() => {
      wx.$toast('提交成功');
    })

  },

  //获取详细数据
  getDetailData(){
    return new Promise(resolve => {
      let where = [{CompareValue: this.data.row_id, CompareWith: "muck_order_main.row_id", Operator: "=", or: 0}],
        fieldList = ['row_id','XuYaoTianTuZhiWeiZhi'];
      fieldList = fieldList.concat(Object.keys(this.data.mainAuthField))
      this.data.mainField.forEach(item =>{
        let {field_id,children} = item;
        let id = field_id && field_id.split(';')[0]
        if (id) fieldList.push(id)
        if (children && children.length){
          children.forEach(ite =>{
            let {field_id} = ite;
            let id = field_id && field_id.split(';')[0]
            if (id) fieldList.push(id)
          })
        }
      })
      // 获取主表数据
      this.getCustomData('muck_order_main',where,fieldList.join(',')).then(data =>{
        console.log(data);
        let formData = data && data[0]
        this.setData({formData})
        resolve();
        this.getDestDetailData(); // 消纳场数据
        // this.getAssignDriver();   // 指派司机数据-- 初始不请求，点击查看时再请求
      })


      /*this.getCustomRow('muck_order_main',this.data.row_id).then(data =>{
        if (data){
          let formData = data.entity[0],
            {detail1,detail2} = data,
            driverDetail = [],destinationAssign = [];
          if (detail1.table_id === 'muck_order_assign_destination') {
            destinationAssign = detail1.entity;
            driverDetail = detail2.entity;
          }else {
            driverDetail = detail1.entity;
            destinationAssign = detail2.entity
          }
          let activeId = [];
          driverDetail.forEach(item => {
            activeId.push(item.reference1_driver)
          });
          this.setData({formData,driverDetail,destinationAssign,activeId})
        }
        resolve();
      })*/

    })
  },
 // 获取指派消纳场数据
  getDestDetailData(){
    return new Promise(resolve => {
      let where = [{CompareValue: this.data.row_id, CompareWith: "muck_order_assign_destination.parent_row_id", Operator: "=", or: 0}],
        fieldList = ['row_id'];
      this.data.destField.forEach(item =>{
        let {field_id,children} = item;
        let id = field_id && field_id.split(';')[0]
        if (id) fieldList.push(id)
        if (children && children.length){
          children.forEach(ite =>{
            let {field_id} = ite;
            let id = field_id && field_id.split(';')[0]
            if (id) fieldList.push(id)
          })
        }
      })
      console.log('this.data.destField', this.data.destField)
      fieldList.push('is_used')
      this.getCustomData('muck_order_assign_destination',where,fieldList.join(',')).then(data =>{
        this.setData({destinationAssign: data || []})
        resolve();
      })
    })
  },
 // 获取工地指派司机数据
  getAssignDriver(){
    return new Promise(resolve => {
      let where = [{CompareValue: this.data.row_id, CompareWith: "muck_order_assign_personnel.parent_row_id", Operator: "=", or: 0}],
        fieldList = ['row_id','reference1_driver'];
      this.getCustomData('muck_order_assign_personnel',where,fieldList.join(',')).then(data =>{
        this.setData({driverDetail: data || []})
        resolve(data || []);
      })
    })

  },

 // 搜索泥尾消纳场
  bindSearchDestination(){
    let {destinationAssign,searchValue} = this.data;
    console.log('搜索内容',searchValue)
    destinationAssign.map(item =>{
      item.isHide = item['reference1_all_destination;value'] && item['reference1_all_destination;value'].indexOf(searchValue.searchDest) === -1;
    });
    this.setData({destinationAssign})

  },

 /* //判断必填项 data:数据项，required必填项对象
  checkRequired(data,required){
    let flag = true;
    Object.keys(required).forEach(item => {
      let value = data[item]
      if (flag && ['',undefined,null].includes(value)){
        wx.$toast(required[item]);
        flag = false;
      }
    })
    return flag;
  },

  //获取diy数据
  getCustomData(table_id,where){
    let url = 'DynamicQuery/query_dynamic_v1',
      post = {limit: 0, page: 1, table_id,obj: `${table_id}.row_id`};
    where && (post.SearchWhere = where);
    return new Promise(resolve => {
      wx.$post(3,url,post).then(res => {
        if (res.errcode != 0) return;
        resolve(res.data.row)
      })
    })
  },
  getCustomRow(table_id,row_id){
    return new Promise(resolve => {
      let url = 'DynamicQuery/query_dynamic_v2',
        post = {row_id,table_id}
      wx.$post(3,url,post).then(res => {
        if (res.errcode != 0) return;
        let data = res.data.row && res.data.row[0];

        resolve(data);
      })
    })
  },
  //获取模块字段
  getCustomField(table_id){
    let url = 'QX/PRO_select_field',
      post = {"table": table_id,"fieldname":""};
    return new Promise(resolve => {
      wx.$post(4,url,post).then(res =>{
        if (res.errcode != 0) return;
        let data = res.data.row || [];
        resolve(data);
      })
    })
  },

  updateCustomData(post){
    return new Promise(resolve => {
      let url = 'DynamicUpdate/dynamic_update_v3';
      wx.$post(3,url,post).then(res =>{
        if (res.errcode != 0) return;
        resolve();

      })
    })
  },

  //提交修改数据
  submitData(table_id,post){
    let url = 'DynamicUpdate/dynamic_update_v2';
    return new Promise(resolve => {
      wx.$post(3,url,post).then(res =>{
        if (res.errcode != 0) return;
        resolve();
      })
    })
  },
  //删除数据
  delData(table_id,data){
    let url = 'DynamicUpdate/dynamic_delete',
      post = {table_id,row_ids: data};
    return new Promise(resolve => {
      wx.$post(3,url,post).then(res => {
        if (res.errcode != 0) return;
        resolve();
      })
    })
  },
*/

    /*231219 yan 注释
    //选择车队
    onClickFirstNav({ detail = {} }) {
      let {index} = detail,
        {items} = this.data,
        item = items[index],
        {child} = item;
      if (!child) {
        this.setDriverLevel(2,item.id,index)
      }

      this.setData({
        firstActiveIndex: index || 0,
        secondActiveIndex: 0
      });
      this.isCheckedAll();
    },
    //选择分队
    onClickSecondNav({ detail = {} }) {
      let {index} = detail,
        {items,firstActiveIndex} = this.data,
        data = items[firstActiveIndex].child[index],
        {children} = data;
      if (!children){
        this.setDriverLevel(3,data.id,index)
      }
      this.setData({
        secondActiveIndex: index || 0,
      });
      this.isCheckedAll();
    },
    //选择司机
    onClickItem({ detail = {} }){
      const { activeId } = this.data;

      const index = activeId.indexOf(detail.id);
      if (index > -1) {
        activeId.splice(index, 1);
      } else {
        activeId.push(detail.id);
      }

      this.setData({ activeId });
      this.isCheckedAll();
    },

    //获取司机分级信息
    getDriverLevel(post){
      let url = 'ZTAuth/query_driver_inf_lv';
      return new Promise(resolve => {
        wx.showLoading({mask: true})
        wx.$post(5,url,post).then(res => {
          if (res.errcode != 0) return;
          wx.hideLoading()
          let data = res.data.row || [],
            arr = [],
            id = '',text = '',
            idName = '',textName = '';
          if (post.lv === 1){
            idName = 'r_suoshuchedui';textName = 'r_suoshuchedui_value';
          }
          if (post.lv === 2){
            idName = 'suoshufendui';textName = 'suoshufendui_value';
            arr.push({
              text: '全部',
              id: 'all'
            })
          }
          if (post.lv === 3){
            idName = 'row_id';textName = ['dengxianghao','chelianghaoma','jiashiyuanxingming'];
          }
          data.forEach(item => {
            let text = '';
            if (typeof textName === 'object'){
              text = [];
              textName.forEach(ite => {item[ite] && text.push(item[ite])});
              text = text.join('-');
            }else {
              text = item[textName];
            }
            arr.push({
              text,
              id: item[idName]
            })
          })
          resolve(arr)
        })
      })
    },

    setDriverLevel(lv,id,index){
      let {firstActiveIndex,secondActiveIndex,items} = this.data;
      //车队
      if (lv === 1){
        this.getDriverLevel({lv: 1}).then(res =>{
          let arr = res;
          this.setData({items: arr})
          if (arr[0]){
            this.setDriverLevel(2,arr[0].id,0)
          }
        })
      }
      //分队
      if (lv === 2){
        let post = {lv: 2,lv_1_row_id: id}
        this.getDriverLevel({lv: 2,lv_1_row_id: id}).then(res => {
          this.setData({[`items[${index}].child`]: res});
          if (res[0]){
            this.setDriverLevel(3,res[0].id,0)
          }
        })
      }
      //司机
      if (lv === 3){
        let post = {lv: 3,lv_1_row_id: items[firstActiveIndex].id};
        post.lv_2_row_id = id === 'all' ? '' : id;
        this.getDriverLevel(post).then(res => {
          this.setData({[`items[${firstActiveIndex}].child[${index}].children`]: res});
          this.isCheckedAll();
        })
      }
    },
    //全选司机
    checkAllDriver({detail}){
      let {items,firstActiveIndex,secondActiveIndex,activeId} = this.data;
      let drivers = items[firstActiveIndex].child[secondActiveIndex].children;

      drivers.forEach(item =>{
        let index = activeId.indexOf(item.id);
        if (detail && index < 0){
          activeId.push(item.id)
        }
        if (!detail && index >= 0){
          activeId.splice(index, 1);
        }
      })

      this.setData({checkAll: detail,activeId});
    },
    isCheckedAll(){
      const { activeId,items,firstActiveIndex,secondActiveIndex, } = this.data;
      let drivers = items[firstActiveIndex].child[secondActiveIndex].children;
      if (!drivers)return;
      let checkAll = drivers.every(item => activeId.includes(item.id));
      this.setData({ checkAll });
    },*/

  //231219 yan 修改车队选择样式由分类选择改为弹出选择器选择分队
  //选择司机
 /* onClickItem(e){
    const { activeId, } = this.data;
    let {id} = e.currentTarget.dataset;

    const index = activeId.indexOf(id);
    if (index > -1) {
      activeId.splice(index, 1);
    } else {
      activeId.push(id);
    }

    this.setData({ activeId });
    this.isCheckedAll();
  },

 /!* //获取司机分级信息
  getDriverLevel(post){
    let url = 'ZTAuth/query_driver_inf_lv';
    return new Promise(resolve => {
      wx.showLoading({mask: true})
      wx.$post(5,url,post).then(res => {
        if (res.errcode != 0) return;
        wx.hideLoading()
        let data = res.data.row || [],
          arr = [],
          id = '',text = '',
          idName = '',textName = '';
        if (post.lv === 1){
          idName = 'r_suoshuchedui';textName = 'r_suoshuchedui_value';
          arr.push({
            text: '全部',
            id: 'all'
          })
        }
        if (post.lv === 2){
          idName = 'suoshufendui';textName = 'suoshufendui_value';
          arr.push({
            text: '全部',
            id: 'all'
          })
        }
        if (post.lv === 3){
          idName = 'row_id';textName = ['dengxianghao','chelianghaoma','jiashiyuanxingming'];
        }
        data.forEach(item => {
          let id = item[idName];
          if (!id) return;
          let text = '';
          if (typeof textName === 'object'){
            text = [];
            textName.forEach(ite => {item[ite] && text.push(item[ite])});
            text = text.join('-');
          }else {
            text = item[textName] || '';
          }
          arr.push({
            text,
            id
          })
        });
        resolve(arr)
      })
    })
  },
  //设置显示车队司机
  setDriverLevel(lv,id,id2){
    let {firstActiveIndex,secondActiveIndex,items} = this.data;
    //车队
    if (lv === 1){
      this.getDriverLevel({lv: 1}).then(res =>{
        //231218 yan 增加车队选择器选项
        this.setData({items: res,[`carTeamColumns[0].values`]: res})
        //231218 end
        //默认加载下级分队
        if (res[0]){
          this.setDriverLevel(2,res[0].id,)
        }
      })
    }
    let first = items.filter(item => item.id === id)[0] //一级车队
    //分队
    if (lv === 2){
      let child = first && first.child;
      if (child){
        this.setData({[`carTeamColumns[1].values`]: child});
        return
      }
      let post = {lv: 2};
      post.lv_1_row_id = id === 'all' ? '' : id;
      this.getDriverLevel(post).then(res => {
        //231218 yan 增加车队选择器选项
        let item = items.filter(ite => ite.id === id)[0];
        item.child = res;
        // this.setData({[`items[${index}].child`]: res});
        this.setData({items,[`carTeamColumns[1].values`]: res});


        /!*注释 不需要默认加载
        if (res[0]){
          this.setDriverLevel(3,id,res[0].id)
        }*!/
        //231218 end
      })
    }
    //司机
    if (lv === 3){
      let second = first && first.child.filter(item =>  item.id === id2)[0] //二级车队
      let child = second.children || [];
      if (child.length){
        //清空搜索条件
        child.map(item => item.isHide = false);
        this.setData({crtDriver: child});
        this.isCheckedAll();//检查是否全选，勾起
        return
      }
      let post = {lv: 3};
      post.lv_1_row_id = id === 'all' ? '' : id;
      post.lv_2_row_id = id2 === 'all' ? '' : id2;
      this.getDriverLevel(post).then(res => {
        let item = items.filter(ite => ite.id === id)[0],
          child = item && item.child,
          item2 = child && child.filter(ite => ite.id === id2)[0];
        if (!item2) return;
        item2.children = res;
        item.child = child;
        // this.setData({[`items[${firstActiveIndex}].child[${index}].children`]: res});
        this.setData({items,crtDriver: res});
        this.isCheckedAll();  //检查是否全选，勾起
        // this.setData({items});
      })
    }
  },
  //全选司机
  checkAllDriver({detail}){
    let {items,firstActiveIndex,secondActiveIndex,activeId,driverPickerValue,crtDriver} = this.data;

    // 231219 yan 修改全选司机
    // let drivers = items[firstActiveIndex].child[secondActiveIndex].children;
    // drivers.forEach(item =>{
    crtDriver.forEach(item =>{
      if (item.isHide) return   //已隐藏的不全选
      let index = activeId.indexOf(item.id);
      if (detail && index < 0){
        activeId.push(item.id)
      }
      if (!detail && index >= 0){
        activeId.splice(index, 1);
      }
    })
    //231219 end

    this.setData({checkAll: detail,activeId});
  },
  //检车当前显示的司机是否已全选
  isCheckedAll(){
    const { activeId,crtDriver,items,firstActiveIndex,secondActiveIndex, } = this.data;
    /!*let first = items[firstActiveIndex],
      second = first && first.child && first.child[secondActiveIndex],
      drivers = second && second.children;
    if (!drivers)return;*!/
    let showAll = crtDriver.filter(item => !item.isHide),
      checkAll = showAll.every(item => activeId.includes(item.id));
    this.setData({ checkAll });
  },
  //车队选择器变化
  onColumnsChange(e){
    const { picker, value, index } = e.detail;
    let {items} = this.data,
      item = items[index],
      {child} = item;
    // let first = items.filter(item => item.id === value[0].id)[0] //一级车队
    //车队（一级）
    if (!index){
      this.setDriverLevel(2,value[0].id)
      /!*let child = first.child;
      if (!child) {
        this.setDriverLevel(2,first.id)
      }else {
        this.setData({[`carTeamColumns[1].values`]: child});
      }*!/
    }
    //分队（二级）
    else {
      /!*let second = first.child.filter(item =>  item.id === value[1].id)[0] //二级车队
      let child = second.children;
      if (!child){
        this.setDriverLevel(3,first.id,second.id)
      }*!/

      // this.setDriverLevel(3,value[0].id,value[1].id)

    }
    // picker.setColumnValues(1, citys[value[0]]);
  },*!/
  //选择器确定显示司机
  bindConfirmDriverPicker(e){
    const { picker, value, index } = e.detail;
    this.setDriverLevel(3,value[0].id,value[1].id);
    this.setData({showDriverPicker: false,driverPickerValue: value})
  },
  //显示泥尾指定司机
  async bindShowDriver(e){
    let {index} = e.currentTarget.dataset,
      {items,destinationDetail,addDestDriver} = this.data,
      obj = {},
      first = items[0],
      second = first && first.child && first.child[0];
    obj.driverPickerValue = [first,second];
    this.setDriverLevel(3,first.id,second.id)
    obj.showDriver = true;
    obj.curtPickerIndex = index;  //记录当前泥尾索引
    let activeId = [];
    if (index === 'addDest') {
      activeId = addDestDriver;
    }else {
      let destItem = destinationDetail[index],
        details = destItem.details || [];
      if (!details.length) {
        await this.getDestDriverDetl(destItem.row_id).then(res => {
          details = res;
          obj[`destinationDetail[${index}].details`] = res;
        })
      }
      details.forEach(item =>{activeId.push(item.reference1_driver)})
    }
    obj.activeId = [...activeId];  //显示当前泥尾已选司机

    this.setData(obj);
    this.isCheckedAll();
  },
 /!* //显示车队司机选择器
  bindShowDriverPicker(e){
    this.setData({showDriverPicker: true})
  },
  //收起车队司机选择器
  bindCloseDriverPicker(){
    this.setData({showDriverPicker: false})
  },*!/
  //泥尾指定司机变化更新
  destDriverChange(){
    let {activeId, curtPickerIndex,destinationAssign} = this.data;
    console.log(curtPickerIndex);
    this.setData({[`destinationAssign[${curtPickerIndex}].details`]: [...activeId]});
  },

 /!* //获取泥尾司机明细表资料
  getDestDriverDetl(id){
    return new Promise(resolve => {
      wx.showLoading({mask: true})
      this.getCustomRow('muck_order_assign_destination',id).then(data =>{
        wx.hideLoading();
        if (data){
          let rowData = data.entity[0],
            {detail1,detail2} = data,
            driverDetail = [],destinationDetail = [];
          if (detail1.table_id === 'muck_order_assign_destination_personnel') {
            driverDetail = detail1.entity;
          }else {
            driverDetail = detail2.entity;
          }

          resolve(driverDetail);
          return
        }
        resolve([]);
      })
    })
  },*!/

*/


  //基础数据
  ready(){
    // this.setDriverLevel(1);
    this.getCustomField('muck_order_assign_destination').then(res => {
      let destinationDefData = {
          row_id: 0,
          reference1_all_destination: '',
          reference1_goods: '',
          construction_payment: '应收',
          destination_payment: '应付',
          driver_payment: '应付',
          extra_payment: '应付',
          Order_amount: '',
          driver_price: '',
          extra_price: '',
          is_used: true
        },
        fieldArr = ["construction_payment",'destination_payment','driver_payment','extra_payment','need_fill_excavator_img_end','need_fill_excavator_no_end','need_fill_order_no_end','need_fill_order_img_end'];

      res.forEach(item => {
        let {field_id,option,defaultValue,type} = item;
        if (fieldArr.includes(field_id)) {
          if (type === 'bit')destinationDefData[field_id] = !!defaultValue;
          else {
            let opts = option && JSON.parse(option),
              def = opts && opts.find(ite => ite.isDefault);
            destinationDefData[field_id] = def && def.label || '应付';
          }
        }
      });
      this.setData({
        destinationDefData,
        addDestination: destinationDefData
      })
    })
    // return Promise.all([this.getProject(),this.getDelivery(),this.getDestination(),this.getGoods(),this.getClient(),this.getDestClient()])
    // return Promise.all([this.getProject(),this.getDelivery(),this.getDestination(),this.getGoods()])
    // return Promise.all([this.getDelivery(),this.getDestination(),this.getGoods(),this.getDriver(),])
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let {row_id} = options;
    this.data.row_id = row_id;
    wx.showLoading({mask:true})
    this.getAuthorityList('muck_order_main').then(res=>{
      this.setData({
        auth: res,
      });
      this.initField();
      this.getDetailData().then(() => {
        // this.ready().then(() => wx.hideLoading());
        this.ready()
        wx.hideLoading()
      });
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
